var $ = require('jquery');
var url = require('url');
var http = require('http');
var iconv = require('iconv-lite')
var webInterface = require('./webInterface');
var log4js = require('log4js');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/dealRecords.log'), 'dealRecords');
var logger = log4js.getLogger('dealRecords');

// var tbskipMealUrl =
// "http://tbskip.daily.taobao.net/json/promotion.htm?callback=jsonpInitExtension&user_id=2033188194&item_id=1500024764290&meal=1&tmall=1";
var defaultCallback = 'TShop.mods.DealRecord.reload';
var mdskipMealApi = "http://mdskip.taobao.com/extension/dealRecords.htm";
exports.mdskipApi = mdskipMealApi;
exports.tbskipApi = 'http://tbskip.taobao.com/json/show_buyer_list.htm';

var skipCallback = function(jsonObj) {

	return getContent(jsonObj.html)
}

function getContent(dealDom) {
	var obj={};
	var arr = new Array();
	var $dom = $(dealDom);
	var st = $dom.find('caption').html();
	$dom.find('tr').each(function(i,ele){
		if(i != 0){
			arr.push($(ele).html());
		}
	});
	obj.arr=arr;
	obj.st = st;
	return obj;
}


exports.verify = function(tbskipUrl, callback) {

	tbskipUrl = prepareSkipUrl(tbskipUrl);
	var mdskipUrl = convertTbskipApiToMdskipApi(tbskipUrl);
//	logger.error('readUrl: ' + tbskipUrl + "................" + mdskipUrl);
	webInterface.sendRequest(mdskipUrl, tbskipUrl, function(mdskipres,tbskipres) {
		try{
			if(tbskipres.indexOf("showBuyerListInnerForTimeKill") < 0) {
				var tbskipResult = eval(tbskipres);
				var mdskipResult = eval(mdskipres);
				var isEqual = compareObj(tbskipResult, mdskipResult);
				if (!isEqual) {
					logger.error("NotEqual	" + mdskipUrl + "		" + tbskipUrl);
				} else {
					logger.info('equals');
				}
			}
		}catch(e){
			logger.error("Exception:" + mdskipUrl + "	" + tbskipUrl, e);
		}
		if((typeof callback != 'undefined') && callback != null){
			callback();
		}
	},function(error){

		});
}

function convertTbskipApiToMdskipApi(tbskipurl) {

	var tbskipRequest = url.parse(tbskipurl);

	var tbskipParams = tbskipRequest.query;

	var mdskipMealUrl = mdskipMealApi + "?";

	mdskipMealUrl = mdskipMealUrl + tbskipParams;
	return mdskipMealUrl;
}

function compareObj(ob1, ob2) {
	
	if(ob1.st != ob2.st) {
		logger.error("wrong sellcounts !\n" + ob1.st + "\n" + ob2.st + "\n");
		return false;
	}
	if (ob1.arr.length != ob2.arr.length) {
		return false;
	}
	for ( var i = 0; i < ob1.arr.length; i++) {
		var value1 = ob1.arr[i];
		var value2 = ob2.arr[i];
		if(value1 != value2) {
			logger.error("wrong record !\n"+ value1 + "============" + value2);
			return false;
		}
	}

	return true;
}

function prepareSkipUrl(tbskipUrl) {
	tbskipUrl = tbskipUrl.replace('&callback=', '&originalcallback=');
	tbskipUrl = tbskipUrl + "&callback=skipCallback" + "&debug=true";
	return tbskipUrl;
}

